<template>
  <div class="app-header">
    <!-- 左侧区域：折叠按钮和面包屑 -->
    <div class="header-left">
      <!-- 侧边栏折叠按钮 -->
      <el-button 
        type="text" 
        class="sidebar-toggle-btn"
        @click="handleToggleSidebar"
      >
        <el-icon :size="18">
          <Fold v-if="!props.isCollapsed" />
          <Expand v-else />
        </el-icon>
      </el-button>

      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item 
          v-for="(item, index) in breadcrumbList" 
          :key="index"
          :to="index === 0 ? '/' : undefined"
        >
          <el-icon v-if="index === 0"><HomeFilled /></el-icon>
          {{ item }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 右侧区域：用户信息 -->
    <div class="header-right">
      <!-- 系统时间显示 -->
      <div class="system-time">
        <el-icon><Clock /></el-icon>
        <span>{{ currentTime }}</span>
      </div>

      <!-- 用户信息下拉菜单 -->
      <el-dropdown class="user-dropdown" @command="handleUserCommand">
        <div class="user-info">
          <el-avatar :size="32" class="user-avatar">
            <el-icon><User /></el-icon>
          </el-avatar>
          <span class="username">管理员</span>
          <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">
              <el-icon><User /></el-icon>
              个人信息
            </el-dropdown-item>
            <el-dropdown-item divided command="logout">
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 个人信息对话框 -->
    <UserProfile ref="userProfileRef" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Fold,
  Expand,
  HomeFilled,
  Clock,
  User,
  ArrowDown,
  Setting,
  SwitchButton
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import UserProfile from './UserProfile.vue'
import { logout } from '@/api/auth'

const route = useRoute()
const router = useRouter()
const emit = defineEmits(['toggle-sidebar'])
const userProfileRef = ref(null)

// 接收父组件传递的折叠状态
const props = defineProps({
  isCollapsed: {
    type: Boolean,
    default: false
  },
  isMobile: {
    type: Boolean,
    default: false
  }
})

// 当前时间
const currentTime = ref('')
let timeInterval = null

// 面包屑导航列表
const breadcrumbList = computed(() => {
  const breadcrumb = route.meta?.breadcrumb
  if (breadcrumb && Array.isArray(breadcrumb)) {
    return breadcrumb
  }
  // 如果没有配置breadcrumb，使用默认的
  const title = route.meta?.title
  return title ? ['首页', title] : ['首页']
})

// 处理侧边栏折叠切换
const handleToggleSidebar = () => {
  emit('toggle-sidebar')
}

// 处理用户下拉菜单命令
const handleUserCommand = (command) => {
  switch (command) {
    case 'profile':
      openUserProfile()
      break
    case 'settings':
      ElMessage.info('系统设置功能待开发')
      break
    case 'logout':
      handleLogout()
      break
    default:
      break
  }
}

// 打开个人信息对话框
const openUserProfile = () => {
  if (userProfileRef.value) {
    userProfileRef.value.open()
  }
}

// 安全退出登录
const handleLogout = async () => {
  try {
    // 调用退出登录API
    await logout()
    
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    
    // 显示成功消息
    ElMessage.success('退出登录成功')
    
    // 重定向到登录页面
    router.push({ name: 'Login' })
  } catch (error) {
    console.error('退出登录失败', error)
    // 即使API调用失败，也清除本地存储并重定向
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    ElMessage.warning('已退出登录')
    router.push({ name: 'Login' })
  }
}

// 更新当前时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 组件挂载时启动时间更新
onMounted(() => {
  updateTime()
  timeInterval = setInterval(updateTime, 1000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})
</script>

<style scoped>
.app-header {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  background-color: #fff;
}

/* 左侧区域 */
.header-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.sidebar-toggle-btn {
  margin-right: 16px;
  color: #606266;
  font-size: 18px;
}

.sidebar-toggle-btn:hover {
  color: #409EFF;
  background-color: #f5f7fa;
}

.breadcrumb {
  font-size: 14px;
}

.breadcrumb :deep(.el-breadcrumb__item:first-child .el-breadcrumb__inner) {
  color: #409EFF;
  font-weight: 500;
}

/* 右侧区域 */
.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

/* 系统时间 */
.system-time {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  font-size: 14px;
}

/* 用户信息下拉菜单 */
.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.user-avatar {
  background-color: #409EFF;
}

.username {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.dropdown-icon {
  color: #909399;
  font-size: 12px;
  transition: transform 0.3s ease;
}

.user-dropdown.is-active .dropdown-icon {
  transform: rotate(180deg);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-header {
    padding: 0 15px;
  }
  
  .header-right {
    gap: 15px;
  }
  
  .system-time {
    display: none;
  }
  
  .username {
    display: none;
  }
}

@media (max-width: 480px) {
  .app-header {
    padding: 0 10px;
  }
  
  .breadcrumb {
    font-size: 12px;
  }
  
  .breadcrumb :deep(.el-breadcrumb__item) {
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

/* 下拉菜单项图标样式 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  font-size: 16px;
}
</style>